package com.spring.demo8.eg10;

import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author vhans
 */
@ComponentScan
public class SmartInitializingSingletonTest {
    // ApplicationContext自动回调SmartInitializingSingleton接口
    @Test
    public void test() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(SmartInitializingSingletonTest.class); // 通过包扫描注册bean
        System.out.println("开始启动容器");
        context.refresh();
        System.out.println("容器启动成功");
    }

    // 通过api的方式让DefaultListableBeanFactory去回调SmartInitializingSingleton
    @Test
    public void test1() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

        factory.registerBeanDefinition("service1", BeanDefinitionBuilder
                .genericBeanDefinition(Service1.class)
                .getBeanDefinition());

        factory.registerBeanDefinition("service2", BeanDefinitionBuilder
                .genericBeanDefinition(Service2.class)
                .getBeanDefinition());

        factory.registerBeanDefinition("mySmartInitializingSingleton", BeanDefinitionBuilder
                .genericBeanDefinition(MySmartInitializingSingleton.class)
                .getBeanDefinition());

        System.out.println("准备触发所有单例bean初始化");
        // 触发所有单例初始化，并且回调SmartInitializingSingleton#afterSingletonsInstantiated方法
        factory.preInstantiateSingletons();
    }
}
